package com.sdp.right.dr;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.annotation.ViewColumn;
import com.sdp.core.bizc.db.QueryColumn;
import com.sdp.core.bizc.db.QueryRuleEnum;
import com.sdp.core.bizc.db.QueryUtil;
import com.sdp.core.bizc.exception.ApplicationException;
import com.sdp.core.bizc.threadLocal.ContextManager;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.right.cache.keys.RightCacheKeys;
import com.sdp.right.db.sys_dict.service.ISysDictService;

@Component
public class DrDataQuery {
	
	@Autowired
	private ISysDictService iSysDictService;
	
	@Autowired
	private DrFilter drFilter;

	
	public <T>QueryWrapper<T> queryWrapper(Class<T> clazz,String drNo,String accountNo){
		if(StringUtils.isEmpty(accountNo)) {
			accountNo = ContextManager.getContextData(CoreConstantsEnum.token中账号的属性名.getCode());
		}
		
		QueryWrapper<T> queryWrapper = new QueryWrapper<>();
		
		DataCenter dc = new DataCenter();
		List<QueryColumn> qcList = new ArrayList<>();
		dc.setQueryForm(qcList);
		
		Object drEmpRuleCache = iSysDictService.getDictInfo(RightCacheKeys.DR_EMP_CACHE_KEY, drNo,accountNo);
		if(drEmpRuleCache==null || ((List<?>) drEmpRuleCache).size()==0) {
			//根据角色进行数据过滤
			drFilter.roleFilter(dc,drNo, accountNo);
		}else {
			//根据人员过滤
			drFilter.empFilter(dc,drNo, drEmpRuleCache);
		}
		
		//判断是否为视图
		boolean isView = false;
		Field[] fields = clazz.getDeclaredFields();
		Map<String, Field> fieldMap = new HashMap<>();
		for (Field field : fields) {
			if(field.getAnnotation(ViewColumn.class)!=null) {
				isView = true;
			}
			fieldMap.put(field.getName(), field);
		}
		
		
		Field field;
		ViewColumn column;
		TableField tableField;
		String rule = QueryRuleEnum.EQ.getCode();
		try {
			for(QueryColumn qc : qcList) {
				field = fieldMap.get(qc.getField());
				if(!StringUtils.isEmpty(qc.getCondition())) {
					rule = qc.getCondition();
				}
				if (field != null ) {
					if(isView) {
						column = field.getAnnotation(ViewColumn.class);
						if(column!=null) {
							QueryUtil.addQueryByRule(queryWrapper, rule, column.value(), field.getType().toString(), qc.getVal());
						}
					}else {
						tableField = field.getAnnotation(TableField.class);
						if(tableField!=null) {
							QueryUtil.addQueryByRule(queryWrapper, rule, tableField.value(), field.getType().toString(), qc.getVal());
						}
					}
				}
			}
		} catch (Exception e) {
			throw new ApplicationException("##############解析queryform查询条件字段错误！", e);
		}
		
		return queryWrapper;
	}
	
}
